package com.hgm.study.ui.screens

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.placeholder.placeholder
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.hgm.study.extension.OnBottomReached
import com.hgm.study.ui.components.*
import com.hgm.study.ui.components.TopAppBar
import com.hgm.study.viewmodel.ArticleViewModel
import com.hgm.study.viewmodel.MainViewModel
import com.hgm.study.viewmodel.VideoViewModel
import kotlinx.coroutines.launch
import kotlin.math.sign

/**
 * @author    HGM
 * @version   1.0
 */
@Composable
fun StudyScreen(
      vm: MainViewModel = viewModel(),
      articleVM: ArticleViewModel = viewModel(),
      videoVM: VideoViewModel = viewModel(),
      onNavigateToArticle: () -> Unit = {},
      onNavigateToStudyHistory: () -> Unit = {}
) {

      LaunchedEffect(Unit) {
            //获取分类数据
            vm.categoryData()
            //获取文章列表
            articleVM.fetchArticleList()
            //获取视频列表
            videoVM.fetchVideoList()
      }

      val coroutineScope = rememberCoroutineScope()

      val lazyListState = rememberLazyListState()
      lazyListState.OnBottomReached(buffer = 2) {
            Log.e("hgm", "StudyScreen: OnBottomReached")
            coroutineScope.launch {
                  articleVM.loadMore()
            }
      }




      Column(modifier = Modifier) {
            //标题栏
            TopAppBar(modifier = Modifier.padding(horizontal = 8.dp)) {

                  //搜索按钮
                  Surface(
                        modifier = Modifier
                              .clip(RoundedCornerShape(16.dp))
                              .weight(1f),
                        color = Color(0x33FFFFFF)
                  ) {
                        Row(
                              modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                              verticalAlignment = Alignment.CenterVertically
                        ) {
                              Icon(
                                    imageVector = Icons.Default.Search,
                                    contentDescription = null,
                                    tint = Color.White
                              )
                              Text(
                                    text = "搜索感兴趣的资讯或课程",
                                    color = Color.White,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                              )
                        }
                  }

                  //学习进度
                  Text(
                        text = "学习\n进度",
                        fontSize = 11.sp,
                        color = Color.White,
                        modifier = Modifier
                              .padding(horizontal = 4.dp)
                              .clickable { onNavigateToStudyHistory() }
                  )
                  Text(
                        text = "26%",
                        fontSize = 15.sp,
                        color = Color.White,
                        modifier = Modifier.padding(horizontal = 4.dp)
                  )
                  Icon(
                        imageVector = Icons.Default.Notifications,
                        contentDescription = null,
                        tint = Color.White
                  )
            }

            //分类标签
            TabRow(
                  selectedTabIndex = vm.categoryIndex,
                  backgroundColor = Color.White,
                  contentColor = Color(0xFF149EE7)
            ) {
                  vm.categories.forEachIndexed { index, category ->
                        Tab(
                              selected = vm.categoryIndex == index,
                              onClick = {
                                    vm.updateCategoryIndex(index)
                              },
                              selectedContentColor = Color(0xFF149EE7),
                              unselectedContentColor = Color(0xFF666666)
                        ) {
                              Text(
                                    text = category.title,
                                    modifier = Modifier
                                          .padding(
                                                horizontal = 8.dp,
                                                vertical = 12.dp
                                          )
                                          .placeholder(
                                                visible = !vm.categoryLoaded,
                                                color = Color.LightGray
                                          ),
                                    fontSize = 14.sp
                              )
                        }
                  }
            }


            //类型标签
            TabRow(
                  selectedTabIndex = vm.currentTypeIndex,
                  backgroundColor = Color.Transparent,
                  contentColor = Color(0xFF149EE7),
                  indicator = {},
                  divider = {}
            ) {
                  vm.types.forEachIndexed { index, type ->
                        LeadingIconTab(
                              selected = vm.currentTypeIndex == index,
                              onClick = { vm.updateTypeIndex(index) },
                              selectedContentColor = Color(0xFF149EE7),
                              unselectedContentColor = Color(0xFF666666),
                              text = {
                                    Text(
                                          text = type.title,
                                          modifier = Modifier.padding(
                                                horizontal = 8.dp,
                                                vertical = 12.dp
                                          ),
                                          fontSize = 16.sp
                                    )
                              },
                              icon = { Icon(imageVector = type.icon, contentDescription = null) }
                        )
                  }
            }


            SwipeRefresh(
                  state = rememberSwipeRefreshState(isRefreshing = articleVM.refreshing),
                  onRefresh = { coroutineScope.launch { articleVM.refresh() } }
            ) {

                  LazyColumn(state = lazyListState) {
                        //轮播图
                        item { SwiperContent(vm = vm) }

                        //通知栏
                        item { NotificationContent(vm = vm) }


                        if (vm.showArticleList) {
                              //新闻列表
                              items(articleVM.list) { article ->
                                    ArticleItem(
                                          article,
                                          articleVM.listLoader,
                                          modifier = Modifier.clickable { onNavigateToArticle.invoke() }
                                    )
                              }
                        } else {
                              //视频列表
                              items(videoVM.list) { video ->
                                    VideoItem(video)
                              }
                        }
                  }
            }


      }
}

